<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="cache-control" content="max-age=0"/>
<meta http-equiv="cache-control" content="no-cache"/>
<meta http-equiv="expires" content="0"/>
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT"/>
<meta http-equiv="pragma" content="no-cache"/>
<title></title>
<link rel="stylesheet" type="text/css" href="../css/common/admin_templ_style.css"/>
<link rel="stylesheet" type="text/css" href="../api/css/cupertino/jquery-ui-1.10.1.custom.min.css"/>
<link rel="stylesheet" type="text/css" href="../api/css/jquery.colorpicker.css"/>
<script src="../api/js/jquery-1.8.3.js" type="text/javascript"></script>
<script src="../api/js/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<script type="text/javascript" src="../api/js/jquery.colorpicker.js"></script>
<script type='text/JavaScript' src='../../zbw_reporting/scripts/framework_include.js'></script>
<script type='text/JavaScript' src='../theme_engine/lib/jquery-xml2json/src/xml2json.js'></script>
<script type="text/javascript" src="../api/js/jquery.colorpicker.js"></script>

<script type="text/javascript" src="../theme_engine/lib/jscssp/cssParser.js"></script>

<!-- fancytree -->
<script src="../theme_engine/lib/fancytree/src/jquery.fancytree.js"></script>
<script src="../theme_engine/lib/fancytree/src/jquery.fancytree.filter.js"></script>
<script src="../theme_engine/lib/fancytree/src/jquery.fancytree.table.js"></script>
<link rel="stylesheet" href="../theme_engine/lib/fancytree/src/skin-lion/ui.fancytree.css"/>
<link rel="stylesheet" href="../theme_engine/style/onepcssgrid.css"/>

<script src="../theme_engine/vo/AdminTreeToConfigVO.js"></script>
<script src="../theme_engine/vo/ConfigVOToAdminTree.js"></script>


<script type="text/javascript">

var ENGINE_CONFIG = {
    WIRZRD_CONIG_URL:"../theme_engine/mock/test.json",
    CSS_URL : "../theme_engine/themes/theme01/Style.css",
    TARGET_IFRAME_URL:"theme_preview3.htm"
}

var IFRAME_ID = "#iframe";
var configData = {};
var flatCSS = []; // Css from url


function PraseCss(cssString) {
    var parser = new CSSParser();
    var sheet = parser.parse(cssString, false, true);
    return GetCssToFlatArray(sheet.cssRules);
}

// Upadte Css in config file with new css
function BindCssFromFileIntoConfig(propertiesList, flatCSS)
{
    for(var x = 0; x < propertiesList.length; x++)
    {
        for(var y = 0; y < flatCSS.length; y++)
        {
            var selector = propertiesList[x].selectors;
            var property = propertiesList[x].css;

            if((selector === flatCSS[y].selector) &&
                    (property === flatCSS[y].property))
            {
                var value = flatCSS[y].value !== undefined ? flatCSS[y].value : "";
                propertiesList[x].value = value;
            }
        }
    }
    return propertiesList;
}


function BindCssFromPropListIntoWizard(propertiesList)
{
    for(var x = 0; x < propertiesList.length; x++)
    {
        var propName = propertiesList[x]['property'];
        var propSelector = propertiesList[x]['selector'];
        var matchedList = $('[name="'+ propName + '"]');

        if(matchedList.length > 0)
        {
            for(var y=0; y < matchedList.length; y++)
            {
                var selector = matchedList[y].parentNode.attributes.name.nodeValue;

                if(propSelector === selector)
                {
                    $(matchedList[y]).val(propertiesList[x].value);
                    break;
                }
            }
        }
    }
}

function ApplyCssFromFlatCssList(flatCSS)
{
    for(var x = 0; x < flatCSS.length; x++)
    {
        $( flatCSS[x].selector).css(flatCSS[x].property, flatCSS[x].value);
    }
}

/* Load wizard configuration from ENGINE_CONFIG.WIRZRD_CONIG_URL */
function LoadAppFromConfigService(url) {
    $.ajax({
        type:"GET",
        data:{
        },
        url:url,
        dataType:"text",
        success:function (data) {
            //manipulate the data
            configData = $.xml2json(data);
            //mnbnnnbmnbnmnbnnbvcbnm = GetAllProperties(configData);
            var accord = BuildAccordion(configData);
             $(accord).appendTo("#div1");

            //Initialize the colorpicker component
            $('.color-picker').colorpicker(
                    {
                        parts:'full',
                        alpha:true,
                        showOn:'both',
                        buttonColorize:true,
                        showNoneButton:false,

                    });
            //CSS
          //   setTimeout('ApplyTheDefaultCssFromConfig(propertiesList, IFRAME_ID)', 300);
        },
        error:function (error) {
            // show the error details or show a user friendly error message
            alert("Due to unexpected errors we were unable to load data");

        }
    });
}

function LoadCssService(url) {
    $.ajax({
        type:"GET",
        data:{
        },
        url:url,
        dataType:"text",
        contentType:"application/json; charset=utf-8",
        success:function (data) {
            var result = data;
            flatCSS = PraseCss(result);
      //      BindCssFromFileIntoConfig(propertiesList, flatCSS);
            BindCssFromPropListIntoWizard(flatCSS);
            setTimeout('ApplyTheDefaultCssFromFile(flatCSS, IFRAME_ID)', 300);
        },
        error:function (error) {
            // show the error details or show a user friendly error message
            alert("Due to unexpected errors we were unable to load css data");
        }
    });
}

function LoadJsonFile(url, success_callback, fail_callback) {
    $.ajax({
        type:"GET",
        data:{
        },
        url:url,
        dataType:"json",
        contentType:"application/json; charset=utf-8",
        success:function (data) {

            success_callback(data);

        },
        error:function (error) {
            fail_callback(error);
            // show the error details or show a user friendly error message
            alert("Due to unexpected errors we were unable to load css data");
        }
    });
}

// return selector, property, value
function GetCssToFlatArray(cssFilePropList) {
    var result = [];
    for(var x = 0; x < cssFilePropList.length;  x++)
    {
        if(cssFilePropList[x].type === 1)
        {
            var selector  = cssFilePropList[x].mSelectorText;
            for(var y = 0 ; y < cssFilePropList[x].declarations.length; y++)
            {
                var property = cssFilePropList[x].declarations[y].property;
                var valueText = cssFilePropList[x].declarations[y].valueText;

                var obj = {'selector': selector, 'property': property, 'value':valueText};
                result.push(obj)
            }
        }
    }
    return result;
}

/* Parse the default CSS properties from the configuration file */
function GetAllProperties(data) {
    var result = [];
    for (var x = 0; x < data.length; x++) {
        for (var y = 0; y < data[x].properties.length; y++) {
            result.push(data[x].properties[y]);
        }
    }
    return result;
}

/* Bulding Accordion */
    function BuildAccordion(result) {
    var accordion = $('<div id="accordion3"></div>');
    for (var x = 0; x < result.root.node.length; x++) {
        var selector = result.root.node[x].node.$.value;
        var groupName = result.root.node[x].$.text;
        var h3 = '<h3> ' + groupName + '</h3>'; //Group Text
        $(h3).appendTo(accordion);
        var properties = "";

        var content = $("<div/>",
                {   name:selector
                });

        for (var y = 0; y < result.root.node[x].node.node.length; y++) {
            var property = result.root.node[x].node.node[y].$;
            var field = BuildAccordionField(property, selector);
            $(field).appendTo(content);
        }
        $(content).appendTo(accordion);
    }

    $(accordion).appendTo("body");
    $(accordion).accordion({collapsible:true, heightStyle:"content", animate:200});
    return $(accordion);
}


function BuildAccordionField(obj, selector) {
    var label = $('<label>' + obj.label + '</label>');

    var content = $("<div/>",
            {   name:selector,
                class: "theme-edit-content"
            });

    $(label).appendTo(content);
    content.append(BuildInputComponent(obj));

    return content;
}
function BuildInputComponent(obj) {

    //Color Picker Select
    if((obj.property).indexOf("color") != -1)
    {
        return BuildColorPicker(obj);
    }
    //Textbox Select
    else if (obj.selectionType === "text")
        return BuildTextInput(obj);
    //Dropdown Select
    else if (obj.selectionType === "select")
        return BuildDropDownSelect(obj);


    return;
}
/* Build textinput for the wizard */
function BuildTextInput(obj) {
    var content = $("<input/>",
            {   id:obj.id,
                type:obj.selectionType,
                name:obj.property,
                value:obj.value,
                keyup:InputComponentChangeHandler
            });
    return content;
}
/* Build select for the wizard */
function BuildDropDownSelect(obj) {
    //obj is the list of option values
    var content = $('<select/>',
            {
                id:obj.id,
                name:obj.property,
                change:InputComponentChangeHandler
            });

    var options = obj.options.split(",");
    for (var x = 0; x < options.length; x++) {
        if ((options[x]).trim() === obj.value) {
            content.append(
                    $('<option selected>' + options[x].trim() + '</option>',
                            { value:options[x].trim()
                            }
                    )
            );
        }
        else {
            content.append(
                    $('<option>' + options[x].trim() + '</option>',
                            { value:options[x].trim()
                            }
                    )
            );
        }
    }

    $('select option[value="' + obj.value + '"]').attr("selected", true);
    //$('select option[value="1"]').attr("selected",true);
    return content;
}
/* Apply CSS stored in config into the preview page */

/*Build Color Picker*/
function BuildColorPicker(obj) {
    var content = $("<input/>",
            {   id:obj.id,
                type:obj.selectionType,
                name:obj.property,
                value:obj.value,
                keyup:InputComponentChangeHandler,
                class: "color-picker"


            });


    return content;
}
function ApplyTheDefaultCssFromConfig(propertiesList, iframeID) {
    for (var x = 0; x < propertiesList.length; x++) {
        var obj = propertiesList[x];
        if (iframeID === undefined)
            $(obj.selectors).css(obj.css, obj.value);

        else // Apply CSS on Iframe
            $(iframeID).contents().find(obj.selectors).css(obj.css, obj.value);
    }
}

function ApplyTheDefaultCssFromFile(propertiesList, iframeID) {
    for (var x = 0; x < propertiesList.length; x++) {
        var obj = propertiesList[x];
        if (iframeID === undefined)
            $(obj.selectors).css(obj.property, obj.value);

        else // Apply CSS on Iframe
            $(iframeID).contents().find(obj.selector).css(obj.property, obj.value);
    }
}

/* Input Handlers */
function InputComponentChangeHandler(e) {
    if (e.currentTarget.type === "text")
        TextInputChangeHandler(e);
    else if (e.currentTarget.type === "select-one")
        SelectInputChangeHandler(e);
}
function SelectInputChangeHandler(e) {
    //up key
    if (e.keyCode == '38') {

    }

    //down down
    else if (e.keyCode == '40') {

    }

    var value = e.currentTarget.value;
    var property = e.target.name;
    var selector = e.currentTarget.parentNode.attributes.name.nodeValue;

    ApplyCssChanges(selector, property, value, IFRAME_ID);

    BindWizardChangesIntoPropList(selector, property, value, flatCSS);

}

function BindWizardChangesIntoPropList(selector, property, value, propList)
{
    for(var x =0; x < propList.length; x++)
    {
        if(propList[x].selector === selector && propList[x].property === property)
        {
            propList[x].value = value;
            break;
        }
    }
}

function TextInputChangeHandler(e) {
    var value = e.currentTarget.value;
    var property = e.target.name;
    var selector = e.currentTarget.parentNode.attributes.name.nodeValue;

    ApplyCssChanges(selector, property, value, IFRAME_ID);
    BindWizardChangesIntoPropList(selector, property, value, flatCSS);
}

/* Bind CSS changes from the wizard into the preview */
function ApplyCssChanges(selector, property, value, iframeID)
{
    if (iframeID === undefined)
        $(selector).css(property, value);

    else // Apply CSS on Iframe
        $(iframeID).contents().find(selector).css(property, value);
}

/* Export CSS from the wizard into String */
function GetCSS(propertiesList, showEmpty) {
    var groupedCSS = GetGroupedCSSProp(propertiesList, false);
    return ExportGroupedCssPropToString(groupedCSS);
}

function GetGroupedCSSProp(propertiesList, showEmpty) {
    var result = {};
    var propListGroup = {};
    for (var x = 0; x < propertiesList.length; x++) {
        var selector = (propertiesList[x].selector).trim();
        var css = (propertiesList[x].property).trim();
        var value = (propertiesList[x].value).trim();
        ;

        if (result[selector] === undefined)
            result[selector] = [];

        if (showEmpty)
            result[selector].push(css + ":" + value + ";");
        else if (value != "")
            result[selector].push(css + ":" + value + ";");

    }
    return result;
}
function ExportGroupedCssPropToString(groupedCSS) {
    var result = "";
    for (var key in groupedCSS) {
        result += key + " {" + "\n";
        for (var x = 0; x < groupedCSS[key].length; x++) {
            result += "\t" + groupedCSS[key][x] + "\n";
        }
        result += "}" + "\n";
    }
    return result;
}

/* Saving CSS*/
function SaveCSS(propertiesList, showEmpty) {
    var result = GetCSS(propertiesList, showEmpty);
    alert(result);
}

/* Initalize Application*/

function BuildTree(data) {
    $("#tree").fancytree({
        extensions:["filter"],
        source:data,
        icons: true,

        filter:{
            mode:"hide"
        },
        activate:function (e, data) {
            var node = $("#tree").fancytree("getActiveNode");
            var d = node.toDict(true, function(dict){
                // Remove keys, so they will be re-generated when this dict is
                // passed to addChildren()
                delete dict.key;
            });
            var selectedDic =  JSON.stringify(d);

            $("#output").val(selectedDic) ;

            $("#outputUI").empty();
            $("#outputUI").append(CreateForm(d.data));

        },

        expand: function(event, data) {},

        collapse: function(event, data) {},

        init:function (event, data) {
            $("#tree").fancytree("getRootNode").visit(function(node){
                node.setExpanded(true);
            });
        }
    });
}

function CreatePropertyData() {
    var newData = {
        "title": "NEW PROPERTY",
        "type" : "property",
        "property" : "NEW PROPERTY",
        "value" : "",
        "label": "Bg Image",
        "component" : "",
        "selectionType" : "text",
        "options" : "",
        "isNumric" : "0"
    }
    return newData;
}

function CreateSelectorData() {
    var newData = {
        "title": "NEW SELECTOR",
        "value" : "NEW SELECTOR",
        "type" : "selector",
        "folder" : "true"
    }
    return newData;
}

function CreateGroupData() {
    var newData = {
        "title": "NEW GROUP",
        "text" : "NEW GROUP",
        "type" : "group",
        "folder" : "true"
    }
    return newData;
}


function GenerateTreeDataProvider(data) {
    var a = new ConfigVOToAdminTree(data);
    var dataProvider = a.GetTreeDataProvider();
    BuildTree(dataProvider);
}

$(document).ready(function () {


   // LoadJsonFile("../theme_engine/mock/treeData.json", BuildTree);
    LoadJsonFile (ENGINE_CONFIG.WIRZRD_CONIG_URL, GenerateTreeDataProvider);

    $("#config_url").val(ENGINE_CONFIG.WIRZRD_CONIG_URL);
    $("#config_url").keyup( function(data) {
        ENGINE_CONFIG.WIRZRD_CONIG_URL = data;
    });

    $("#add").click(function() {
        var tree = $("#tree").fancytree("getTree");
        var node = tree.getActiveNode();

        if(node != undefined)
        {
            if(node.data.type === "selector")
            {
                node.addChildren(CreatePropertyData()) ;
            }
            else if (node.data.type === "group")
            {
                node.addChildren(CreateSelectorData()) ;
            }
        }

       else
        {
            node = $("#tree").fancytree("getRootNode");
            node.addChildren(CreateGroupData()) ;//node.appendSibling(newData);
        }
    });

    $("#group").click(function() {
        var node = $("#tree").fancytree("getRootNode");
        node.addChildren(CreateGroupData()) ;//node.appendSibling(newData);
    });


    $("#delete").click(function(e) {
        var tree = $("#tree").fancytree("getTree");
        var node = tree.getActiveNode();
        node.remove();
    });

    $("#export").click(function(e) {
        var tree = $("#tree").fancytree("getTree");
        var d = tree.toDict(true);



        var adminTreeToConfigVO = new AdminTreeToConfigVO(d);
        var configData = adminTreeToConfigVO.GetConfigDataProvider();

        alert(JSON.stringify(configData));
    });





    /*LoadAppFromConfigService(ENGINE_CONFIG.WIRZRD_CONIG_URL);


    $(IFRAME_ID).attr("src", ENGINE_CONFIG.TARGET_IFRAME_URL);
    $("#tabs").tabs();
    $("#tabs_preview").tabs();
    $("#div1").css("height", $(window).height() - 128);
    LoadCssService(ENGINE_CONFIG.CSS_URL);


    $("#grey_theme").click(function() {

        ENGINE_CONFIG.CSS_URL = "../theme_engine/themes/theme01/Style.css";
        LoadCssService(ENGINE_CONFIG.CSS_URL);
    });

    $("#green_theme").click(function() {
        ENGINE_CONFIG.CSS_URL = "../theme_engine/themes/theme02/Style.css";
        LoadCssService(ENGINE_CONFIG.CSS_URL);
    });

    $("#blue_theme").click(function() {

        ENGINE_CONFIG.CSS_URL = "../theme_engine/themes/theme03/Style.css";
        LoadCssService(ENGINE_CONFIG.CSS_URL);
    });

    $("#yellow_theme").click(function() {

        ENGINE_CONFIG.CSS_URL = "../theme_engine/themes/theme04/Style.css";
        LoadCssService(ENGINE_CONFIG.CSS_URL);
    });

    $("#transparent_theme").click(function() {

        ENGINE_CONFIG.CSS_URL = "../admin/themes/theme05/Style.css";
        LoadCssService(ENGINE_CONFIG.CSS_URL);
    });

    $('.color-picker').change(function() {
        alert( "Handler for .change() called." );
    });*/


});


function UpdateInputHandler(data) {
    var tree = $("#tree").fancytree("getTree");
    var node = tree.getActiveNode();
    var name = data.target.name;
    var value = data.target.value ;

    if(node.data.type === "property" && this.name === "property")
        node.setTitle(value);

    else if(node.data.type === "selector" && this.name === "value")
        node.setTitle(value);

    else if(node.data.type === "group" && this.name === "text")
        node.setTitle(value);

    node.data[this.name] = value;
}

function CreateForm(data) {
    var container = $("<ul/>");
    for (var prop in data) {

        var singleRow = $("<li/>", {
            class: "onerow"
        });

        var label = $("<label>", {
            class: "col3"
        }).text(prop);

        var content = $("<input/>",
                {   type:data.selectionType,
                    name:prop,
                    value: data[prop],
                    type:    "text",
                    keyup: UpdateInputHandler,
                    class: "col9 last",
                    readonly: prop === "type"? true: false
                });

        $(label).appendTo(singleRow);
        $(content).appendTo(singleRow);
        $(singleRow).appendTo(container);
    }
    return container;
}
</script>

<style type="text/css">
    body {
        background: none;
        height: 100%;
    }

    #theme-edit-form {
        height: calc(100% -42px);
    }

    #theme-edit-form h2 {
        margin-bottom: 20px;
    }

    #theme-edit-form h3.ui-accordion-header-active {
        color: #fff;
    }

    #theme-edit-form select {
        padding-left: 0;
        white-space: nowrap;
    }

    #theme-edit-form input[type="file"] {
        width: 132px;
    }

    .theme-edit-block {
        margin-left: 10px;
        width: 21%;
    }

    .ui-accordion .theme-edit-content {
        padding: 0;
    }

    .theme-edit-content ul {
        padding: 20px 5px;
    }

    .theme-edit-content li label {
        font-size: 11px;
        padding-right: 10px;
        width: 35%;
    }

    .theme-edit-content button.ui-state-default {
        background: none;
        border: none;
    }

    .theme-edit-content span.ui-button-text {
        padding: 0;
        font-style: inherit;
    }

    .hidden-field {
        margin: 5px 0;
    }

    .hidden-field input {
        width: 60px;
    }

    .hidden-field select {
        width: 77px;
    }

    .hidden-field span.close {
        padding: 1px 5px;
        display: inline-block;
        background: #aed0ea;
        color: #fff;
        border-radius: 3px;
        margin-left: 5px;
    }

    .hidden-field span.close:hover {
        cursor: pointer;
        background: #4F7891;
    }

    form, .kpi-preview, .kpi-drill {
        border: 1px solid #9CD6E7;
        border-radius: 5px;
        box-shadow: 0 0 100px #AADCEA;
        margin: 0 auto;
        padding-bottom: 50px;
        width: 98%;
    }

        /*  new */
    .left-25 {
        float: left;
        width: calc(25%);
        height: calc(100% -10px);
    }

    .right-75 {
        float: left;
        height: 100%;
        margin-left: 20px;
        width: calc(73% + 4px);
    }

    .tab-frame label {
        margin-left: -33px;
        width: 33%;
    }

    .tab-frame label {
        width: 48%;
    }

    input[type = "text"], select, textarea {
        width: 50%;
    }

    #accordion3 div:not(:first-child) {
        padding-top: 8px;
    }

    .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default {
        font-size: 12px;
        padding: 1px 1px 1px 27px;
    }

    #bi_admin_layout_editor .top-content {
        height: 100%;
    }

    #bi_admin_layout_editor .top-content {
        padding: 0 1px;
    }

    iframe {
        height: calc(100% +59px);
    }

    .ul_prop {
        width: 400px;
        text-align: right;
        float: left;
    }

    .tab-frame ul {
        text-align: left;
    }

    .tab-frame label {
        width: 25%;
    }


</style>

</head>
<body>
<div class="onepcssgrid-1200">
    <div class="onerow">
        <div class="col2">
            <label>Config URL</label>
        </div>
        <div class="col10">
            <div><input type="text"> </div>
        </div>
    </div>
    <div class="onerow">
        <div class="col4">
            <div class="tab-frame" id="bi_admin_report_assign_variables">
                <div class="tab-form">
                    <div class="header">
                        <h2>Wizard Tree</h2>
                        <div id="tree"></div>
                    </div>

                </div>
            </div>
        </div>
        <div class="col8 last">
            <div class="tab-frame">
                <div class="tab-form">
                    <div class="header">
                        <h2>Properties</h2>
                      <!--  <div class="col12">
                            <div id="outputUI"></div>
                        </div>-->

                       <!-- <div id="outputUI"></div>-->
                        <div class="onerow">
                            <div class="col12">
                                <a id="group" href="#">New Group</a>
                                -
                                <a id="add" href="#">Add</a>
                                -
                                <a id="delete" href="#">Delete</a>
                                -
                                <a id="export" href="#">Export</a>
                            </div>
                            <div id="outputUI"></div>
                            </div>
                     <!--   <div class="onerow">
                            <div class="col12">

                            </div>
                        </div>-->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


</body>
</html>